package com.nantai.jiafang.nantaijiafang.deviceManager.devicemanager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.PutRecordAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.RepairRecordAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.Adapter.keepRecordAdapter;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.Device;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.User;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.Error;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.HttpClient;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.preference.PreferencesUtil;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.MessagePop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import info.hoang8f.android.segmented.SegmentedGroup;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class DeviceDetailActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @InjectView(R.id.keep_btn)
    RadioButton mKeepBtn;
    @InjectView(R.id.repair_btn)
    RadioButton mRepairBtn;
    @InjectView(R.id.put_btn)
    RadioButton mPutBtn;
    @InjectView(R.id.segmented2)
    SegmentedGroup mSegmented2;
    @InjectView(R.id.kepplist)
    ListView mKepplist;
    @InjectView(R.id.repairlist)
    ListView mRepairlist;
    @InjectView(R.id.putlist)
    ListView mPutlist;
    @InjectView(R.id.tv_toolbar_title)
    TextView mTvToolbarTitle;
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;

    Device mDevice = null;
    @InjectView(R.id.name_tv)
    TextView mNameTv;
    @InjectView(R.id.qrcode_tv)
    TextView mQrcodeTv;
    @InjectView(R.id.status_tv)
    TextView mStatusTv;
    @InjectView(R.id.place_tv)
    TextView mPlaceTv;

    MaterialDialog showDialog;
    MaterialDialog patrolDialog;

    EditText patrolEdit;
    MaterialSpinner userSpinner;
    List<User> userList;
    User select_user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);
        ButterKnife.inject(this);
        mTvToolbarTitle.setText("巡查");
        mToolbar.setNavigationIcon(R.drawable.md_nav_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mSegmented2.setOnCheckedChangeListener(this);
        mSegmented2.setTintColor(0xFF1b7ce8);
        mSegmented2.check(R.id.put_btn);
        Intent intent = this.getIntent();
        mDevice = (Device) intent.getSerializableExtra("deviceInfo");
        showDialog = new MaterialDialog.Builder(DeviceDetailActivity.this)
                .content("正在请求数据")
                .progress(true, 0, false)
                .cancelable(false).build();

        patrolDialog = new MaterialDialog.Builder(this)
                .title("预警信息")
                .customView(R.layout.patrol_dialog_item, true)
                .positiveText("发送")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        requestCreatePatrol();
                    }
                })
                .build();
        View customView =patrolDialog.getCustomView();
        patrolEdit=(EditText) customView.findViewById(R.id.content_tv);
        userSpinner =(MaterialSpinner) customView.findViewById(R.id.user_spinner);
        userList= PreferencesUtil.getUserList(DeviceDetailActivity.this);
        if(userList==null)
        {
            userList =new ArrayList();
        }
        List user_names = new ArrayList();
        for(User user :userList)
        {
            user_names.add(user.getName());
        }

        userSpinner.setItems(user_names);
        userSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                select_user= userList.get(position);
            }
        });
        if(userList.size()>0)
        {
            select_user=userList.get(0);
        }
        userSpinner.setSelectedIndex(0);
        initView();
    }

    private void initView() {

        mNameTv.setText("设备名称:  " + mDevice.getInfo().getDevice_name());
        mQrcodeTv.setText("设备条码:  " + mDevice.getInfo().getDevice_qrcode());
        mStatusTv.setText("设备状态:  " + mDevice.getInfo().getStatus());
        String place = mDevice.getInfo().getPlace_name();
        mPlaceTv.setText("设备位置:  " + (place == null ? "未知" : place));

        List repairList = mDevice.getRepaire_record();
        if (repairList == null)
            repairList = new ArrayList();

        List putList = mDevice.getPut_record();
        if (putList == null)
            putList = new ArrayList();

        List keepList = mDevice.getKeepup_record();
        if (keepList == null)
            keepList = new ArrayList();

        mRepairlist.setAdapter(new RepairRecordAdapter(repairList, this));
        mRepairlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        mKepplist.setAdapter(new keepRecordAdapter(keepList, this));
        mKepplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        mPutlist.setAdapter(new PutRecordAdapter(putList, this));
        mPutlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.keep_btn: {
                mKepplist.setVisibility(View.VISIBLE);
                mRepairlist.setVisibility(View.GONE);
                mPutlist.setVisibility(View.GONE);
            }
            break;
            case R.id.repair_btn: {
                mKepplist.setVisibility(View.GONE);
                mRepairlist.setVisibility(View.VISIBLE);
                mPutlist.setVisibility(View.GONE);
            }
            break;
            case R.id.put_btn: {
                mKepplist.setVisibility(View.GONE);
                mRepairlist.setVisibility(View.GONE);
                mPutlist.setVisibility(View.VISIBLE);
            }
            break;
            default:
                // Nothing to do
        }
    }

    @OnClick(R.id.send_btn)
    public void onClick() {
        patrolDialog.show();

    }
    private void requestCreatePatrol(){
        String content = patrolEdit.getText().toString();
        if(content==null||content.equals(""))
        {
            MessagePop.ToastMessage(DeviceDetailActivity.this, "请输入预警信息");
            return;
        }
        if(select_user==null)
        {
            MessagePop.ToastMessage(DeviceDetailActivity.this, "请选择解决人选");
            return;
        }
        showDialog.show();
        Map<String, String> params = new HashMap<>();
        params.put("qrcode",mDevice.getInfo().getDevice_qrcode());
        params.put("content",content);
        params.put("operate_user_id",select_user.getId());
        HttpClient client = new HttpClient(DeviceDetailActivity.this);
        Call call = client.service().createPatrol(params);
        client.request(call, new ResponseHandler<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody patrolList) {
                showDialog.dismiss();
                MessagePop.ToastMessage(DeviceDetailActivity.this, "发送预警成功");
            }
            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                if(code!=404)
                {
                    MessagePop.ToastMessage(DeviceDetailActivity.this,e.getMessage());
                }else
                {
                    MessagePop.ToastMessage(DeviceDetailActivity.this, "网络异常");
                }

            }
        });
    }
}
